package com.tang.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * 自定义编码器
 *
 * @author fulin.tang
 * @since 2021/8/22
 */
public class MyEncoder extends MessageToByteEncoder<Object> {

    private static Charset charset;
    
    public MyEncoder() {
        
    }

    public MyEncoder(Charset charset) {
        MyEncoder.charset = charset;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object obj, ByteBuf byteBuf) throws Exception {
        
        String msg = obj.toString();
        byte[] bytes = msg.getBytes();

        byte[] send = new byte[bytes.length + 2];
        System.arraycopy(bytes, 0, send, 1, bytes.length);
        send[0] = 0x02; // ASCII 0000 0010， STX，本文开始
        send[send.length - 1] = 0x03; // ASCII 0000 0011，ETX，本文结束

        byteBuf.writeInt(send.length);
        byteBuf.writeBytes(send);

    }

}
